from flask import Flask
from flask import request
from flask import jsonify

app = Flask(__name__)

#version = 1.0
#windows运行命令
#set FLASK_APP=xiaohe
#flask run --host=0.0.0.0
#QQ496631085

import pyttsx3
import hashlib #md5
import pythoncom




@app.route("/")
def xiaohe():
    return "<p>你好!此接口是文字生成语音，用于windows环境，详细联系QQ496631085</p>"




@app.route('/tts', methods=['POST', 'GET'])
def tts():
    error = None
    # return  request.values.get('str')
    if request.method == 'GET':
        if len(request.values.get('str','')) > 0:
            pythoncom.CoInitialize()
            data = ttsget(request.values.get('str'))
            return data #直接返回路径
        else:
            return "nostr"

    if request.method == 'POST':

        if len(request.values.get('str','')) > 0:
            pythoncom.CoInitialize()
            data = ttspost(request.values.get('str'))
            return data #直接返回路径
        else:
            return "nostr"
    return "错误"
    return render_template('login.html', error=error)


def ttsget(data):
    md5 = hashlib.md5(data.encode(encoding='UTF-8')).hexdigest()

    engine = pyttsx3.init()
    volume = engine.getProperty('volume')
    engine.setProperty('volume', volume) #声音大小
    # engine.say('The quick brown fox jumped over the lazy dog.')
    file_name =  md5+'.mp3'
    path = '/' + 'static/' + file_name
    engine.save_to_file(data ,'.'+path)

    engine.runAndWait()
    return path

def ttspost(data):
    md5 = hashlib.md5(data.encode(encoding='UTF-8')).hexdigest()

    engine = pyttsx3.init()
    volume = engine.getProperty('volume')
    engine.setProperty('volume', volume) #声音大小
    # engine.say('The quick brown fox jumped over the lazy dog.')
    file_name =  md5+'.mp3'
    path = '/' + 'static/' + file_name
    engine.save_to_file(data ,'.'+path)

    engine.runAndWait()
    return {"path":path,"file_name":file_name}

